package com.longxi.tianjintianbao.ui.presenter.approval;

import android.text.TextUtils;
import android.view.View;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.model.approval.ApprovalNextNode;
import com.longxi.tianjintianbao.model.approval.NextNode;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.approval.IApprovalSaveAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.widget.PropertyDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by cxw on & 2018/12/13
 */
public class ApprovalSaveAtPresenter extends BasePresenter<IApprovalSaveAtView> {
    public String CHECK_PASS = "1";//通过
    public String CHECK_NO_PASS = "0";//驳回
    public String check = CHECK_PASS;
    public String REJECTNODE_A_STEP = "0";//上一步骤
    public String REJECTNODE_ORIGINATOR = "1";//发起人
    public String rejectnode = REJECTNODE_A_STEP;
    private String nextnodeid = "";
    private String nextnodename = "";
    private String nextnodecheckerid = "";
    private String nextnodecheckername = "";

    private List<NextNode> nextNodes = new ArrayList<>();
    private List<NextNode> nextNodeCheckers = new ArrayList<>();

    public ApprovalSaveAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("审批");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
        mContext.setTvRight("保存");
        check = mContext.getIntent().getStringExtra(AppConst.CHECK);
        if(check.equals(CHECK_PASS)){
            getView().getRadioGroup().check(R.id.rBtnNormal);
        }else if(check.equals(CHECK_NO_PASS)){
            getView().getRadioGroup().check(R.id.rBtnAbnormal);
        }
        showUI();
    }

    /**
     * 显示通过或驳回的不同ui
     */
    public void showUI(){
        if(check.equals(CHECK_PASS)){
            getView().getLlNextNode().setVisibility(View.VISIBLE);
            getView().getLlRejectNode().setVisibility(View.GONE);
            //请求数据
            myApprovalNextNode();
        }else if(check.equals(CHECK_NO_PASS)){
            getView().getLlNextNode().setVisibility(View.GONE);
            getView().getLlRejectNode().setVisibility(View.VISIBLE);
        }
    }

    /**
     * 下一流程步骤
     */
    public void myApprovalNextNode(){
        if(nextNodes.size() != 0 && nextNodeCheckers.size() != 0){
            return;
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", mContext.getIntent().getStringExtra(AppConst.BILLID));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().myApprovalNextNode(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<ApprovalNextNode>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<ApprovalNextNode> result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }

                ApprovalNextNode approvalNextNode = result.getData().get(0);
                if(approvalNextNode == null){
                    return;
                }

                //步骤名字
                nextNodes.clear();
                String[] nextnodeid = approvalNextNode.getNextnodeid().split(",");
                String[] nextnodename = approvalNextNode.getNextnodename().split(",");
                for (int i = 0; i < nextnodeid.length; i++) {
                    nextNodes.add(new NextNode(nextnodeid[i], nextnodename[i]));
                }

                //审批人
                nextNodeCheckers.clear();
                String[] nextnodecheckerid = approvalNextNode.getNextnodecheckerid().split(",");
                String[] nextnodecheckername = approvalNextNode.getNextnodecheckername().split(",");
                for (int i = 0; i < nextnodecheckerid.length; i++) {
                    nextNodeCheckers.add(new NextNode(nextnodecheckerid[i], nextnodecheckername[i]));
                }
            }
        });
    }

    /**
     * MyApprovalSave
     */
    public void myApprovalSave(){
        String content = getView().getEtContent().getText().toString().trim();
        if(TextUtils.isEmpty(content)){
            MyUtils.showToast(getView().getEtContent().getHint().toString());
            return;
        }

        if(check.equals(CHECK_PASS)){
            if(TextUtils.isEmpty(nextnodeid) || TextUtils.isEmpty(nextnodename)){
                MyUtils.showToast("请选择下一步骤");
                return;
            }
            if(TextUtils.isEmpty(nextnodecheckerid) || TextUtils.isEmpty(nextnodecheckername)){
                MyUtils.showToast("请选择下一步骤审批人");
                return;
            }
        }

//        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", mContext.getIntent().getStringExtra(AppConst.BILLID));
            object.put("userid", MyApplication.loginUser.userid);
            object.put("check", check);
            object.put("content", content);
            if(check.equals(CHECK_PASS)) {
                object.put("nextnodeid", nextnodeid);
                object.put("nextnodename", nextnodename);
                object.put("nextnodecheckerid", nextnodecheckerid);
                object.put("nextnodecheckername", nextnodecheckername);
                object.put("rejectnode", "");
            }else {
                object.put("nextnodeid", "");
                object.put("nextnodename", "");
                object.put("nextnodecheckerid", "");
                object.put("nextnodecheckername", "");
                object.put("rejectnode", rejectnode);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String ojbk = "";
        ApiRetrofit.getInstance().myApprovalSave(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    PropertyDialog.Builder nextNodesbuilder;
    public void showNextNodes(){
        if(nextNodesbuilder != null){
            nextNodesbuilder.show();
            nextNodesbuilder.setNextNode(nextNodes);
            return;
        }
        nextNodesbuilder = new PropertyDialog.Builder(mContext);
        nextNodesbuilder.setTitle("请选择下一步骤")
        .setListener(new PropertyDialog.AdapterListener() {
            @Override
            public void onClick(int position) {
                NextNode nextNode = nextNodes.get(position);
                getView().getTvNextNodeName().setText(nextNode.getName());
                nextnodeid = nextNode.getId();
                nextnodename = nextNode.getName();
                nextNodesbuilder.dismiss();
            }
        })
        .create()
        .show();
        nextNodesbuilder.setNextNode(nextNodes);
    }

    PropertyDialog.Builder nextNodeCheckersbuilder;
    public void showNextNodeCheckers(){
        if(nextNodeCheckersbuilder != null){
            nextNodeCheckersbuilder.show();
            nextNodeCheckersbuilder.setNextNode(nextNodeCheckers);
            return;
        }
        nextNodeCheckersbuilder = new PropertyDialog.Builder(mContext);
        nextNodeCheckersbuilder.setTitle("请选择下一步骤审批人")
        .setListener(new PropertyDialog.AdapterListener() {
            @Override
            public void onClick(int position) {
                NextNode nextNode = nextNodeCheckers.get(position);
                getView().getTvNextNodeCheckerName().setText(nextNode.getName());
                nextnodecheckerid = nextNode.getId();
                nextnodecheckername = nextNode.getName();
                nextNodeCheckersbuilder.dismiss();
            }
        })
        .create()
        .show();
        nextNodeCheckersbuilder.setNextNode(nextNodeCheckers);
    }

    @Override
    public void detachView() {
        super.detachView();
        this.nextNodesbuilder = null;
        this.nextNodeCheckersbuilder = null;
        this.nextNodes = null;
        this.nextNodeCheckers = null;
    }
}
